<template>
    <div class='addproduct-container'>
        <el-form :model="spuInfoVo" ref="spuForm">

            <!-- 分类 -->
            <div class="add-category">
                <span>请选择商品分类</span>
                <div>
                    <changecategory @categoryVo="getCategoryVo"
                        :value="[pparengCid, spuInfoVo.parentCid, spuInfoVo.categoryId]">
                    </changecategory>
                </div>
                <div class="chosecategory">
                    您选择的分类为 [<span title="您的商品分类">{{ spuInfoVo.name }}</span>]
                </div>
            </div>
            <!-- 品牌 -->
            <div class="add-brand">
                <span>请选择商品品牌</span>
                <div>
                    <el-select v-model="spuInfoVo.brandId" placeholder="请选择" :disabled="checkBrand"
                        @change="setBrandName()">
                        <el-option v-for="item in brandList " :key="item.name" :label="item.name" :value="item.brandId">
                        </el-option>
                    </el-select>
                </div>
                <div class="chosecategory">
                    您选择的品牌为 [<span title="您的商品品牌">{{ brandName }}</span>]
                </div>
            </div>
            <!-- 品牌售卖商品 -->
            <div class="add-brandSellProduct">
                <span>该品牌旗下可售卖的商品为</span>
                <div>
                    <el-select v-model="brandSellId" placeholder="请选择" :disabled="checkBrandSell"
                        @change="setBrandSellName()">
                        <el-option v-for="item in brandSellList" :key="item.name" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div class="chosecategory">
                    您选择售卖的商品为 [<span title="您将要售卖的商品名称">{{ brandSellName }}</span>]
                </div>
            </div>
            <!-- 属性值 -->
            <div class="add-attr" v-for="attr, i in attrList">
                <div>
                    <span>{{ attr.attrName }}:&nbsp;</span>
                </div>
                <div>
                    <ul>
                        <li v-for="value, j in attr.splitValue" :class="choseAttr[i][j] ? 'choseColor' : ''"
                            @click="choseClick(i, j)">
                            {{ value }}
                        </li>
                    </ul>
                </div>
            </div>

            <!-- 用户上传图片 -->
            <div class="add-productimg">
                <span>请添加您商品的详细图</span>
                <multiUpload :master="master" :value="fileList" @beginUpload="getSonUpload" @input="inputImg"></multiUpload>
            </div>

            <!-- 用户商品详细描述 -->
            <div class="add-productdetail" style="width: 700px">
                <span>输入商品标题和描述</span>
                <el-form-item prop="spuTitle" :rules="[
                    { required: true, message: '商品标题不能为空' },
                    { min: 3, max: 100, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ]" style="padding-bottom: 25px">
                    <el-input v-model="spuInfoVo.spuTitle" placeholder="请输入商品的标题">
                    </el-input>
                </el-form-item>


                <el-form-item prop="spuDetail" :rules="[
                    { required: true, message: '商品描述不能为空' },
                    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
                ]" style="padding-bottom: 10px">
                    <el-input style="font-size: 20px;" v-model="spuInfoVo.spuDetail" type="textarea" resize="none"
                        :autosize="{ minRows: 15, maxRows: 50 }" placeholder="请输入内容">
                    </el-input>
                </el-form-item>

            </div>

            <!-- 提交信息 -->
            <div class="submitInfo">
                <el-form-item prop="price" :rules="[
                    { required: true, message: '价格不能为空' },
                    { type: 'number', message: '价格必须为数字值' }
                ]">
                    <el-input placeholder="请输入商品价格" class="price" v-model.number="spuInfoVo.price"></el-input>
                    <input class="submitbutton" @click="submitInfo('spuForm')" type="button" value="更 新 商 品 数 据">
                </el-form-item>
            </div>

        </el-form>
    </div>
</template>

<script>
import changecategory from '../common/changecategory.vue';

import multiUpload from "../common/multiUpload.vue"

export default {
    // 模块名字
    name: 'updateProduct',
    // 模块数据
    data() {
        return {

            fileList: [],
            spuInfoVo: {
                // categoryVo: [],   // 分类id，名称
                categoryId: '',   //ok
                name: '',      // ok
                parentCid: '',   // ok
                brandId: '',   // 品牌id  ok 
                brandSellName: '',  // 品牌售卖商品名称 ok
                allAttr: [],  //  ok  由分类产生的属性，其中是用户发布商品选中的所有属性的集合
                spuDetail: '',  // 商品详细信息 ok
                spuTitle: '',  // 商品的标题   ok
                imageUrls: [],   // 图片列表   ok
                id: 0,    // 会员id   ok
                price: '',    // 价格    no
                spuId: '',
                skuId: '',
            },

            // 品牌-前台展示
            brandList: [],
            checkBrand: true,
            brandName: '',
            // 品牌售卖商品-前台展示
            brandSellList: [],
            checkBrandSell: true,
            brandSellId: '',
            brandSellName: '',
            // attr
            attrList: [],  // 所有属性的列表
            choseAttr: [],   // 所有可选的值，这是一个值的矩阵
            attrValues: [],  // 获取的商品属性值

            // 上传文件组件传过来的
            sonUpload: null,

            memberVo: [],
            pparengCid: '',
            master: false,

        };
    },
    // 注册组件
    components: {
        changecategory,
        multiUpload,
    },
    methods: {

        // 数据校验成功后开始提交图片
        submitInfo(formName) {
            // 数据校验
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.sonUpload.submit()
                    this.master = !this.master;
                } else {
                    return false;
                }
            });

        },


        // 获得子组件upload对象
        getSonUpload(data) {
            if (this.sonUpload == null)
                this.sonUpload = data;
        },

        // 子组件 上传图片成功后返回所有图片的url后才进行商品发布请求
        inputImg(data) {
            this.spuInfoVo.imageUrls = data
            // 需要组装sku和spu信息
            this.spuInfoVo.id = this.memberVo.id
            this.spuInfoVo.brandSellName = this.brandSellName
            this.getAttrValue()
           
            let spuInfoVo = JSON.parse(JSON.stringify(this.spuInfoVo)) 
            spuInfoVo.spuDetail = spuInfoVo.spuDetail.replaceAll("\n", "<br>")
            //上传成功, 将信息提交后台  , 刷新页面或者前往管理页
            this.$http({
                url: this.$http.adornUrl("/shitou-product/shitouproduct/spuinfo/updateMemberProduct"),
                method: 'post',
                data: this.$http.adornData(spuInfoVo)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '更新商品成功'
                    })
                    this.formatAll()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        // 获得标记的属性的id和值
        getAttrValue() {

            let len = this.choseAttr.length;   // 获得有几个属性【一个属性里面有很多的值，接下来判断选中哪个】
            this.attrValues = []
            let index = -1;
            for (let i = 0; i < len; i++) {
                for (let j = 0; j < this.choseAttr[i].length; j++) {
                    if (this.choseAttr[i][j]) {   // 初始化为false，如果被选中的值，则在对应设为true  
                        this.attrValues[++index] = {
                            id: '',
                            name: '',
                            value: ''
                        }
                        // 获取属性id和属性值和name
                        this.attrValues[index].name = this.attrList[i].attrName
                        this.attrValues[index].id = this.attrList[i].attrId;
                        this.attrValues[index].value = this.attrList[i].splitValue[j];
                    }
                }
            }

            this.spuInfoVo.allAttr = this.attrValues
        },


        // 标记选中属性
        choseClick(i, j) {
            // 如果当前的节点是已经被选中，那么取消选中的，否则
            // 就将该节点设置未选中，并取消之前选中的节点
            if (this.choseAttr[i][j]) {
                this.choseAttr[i][j] = false
            } else {
                // 将这一行的节点都设置为false
                for (let f = 0; f < this.choseAttr[i].length; f++) {
                    this.choseAttr[i][f] = false;
                }
                // 将选中节点置为true
                this.choseAttr[i][j] = true
            }
            // 让数据重新加载
            let temp = this.attrList
            this.attrList = []
            this.attrList = temp
        },


        // 初始化数据---清除属性
        formatAttr() {
            this.attrList = []
            this.choseAttr = []
            this.attrValues = []
        },

        // 初始化数据---清除品牌售卖商品
        formatSellProduct() {
            this.brandSellList = []
            this.checkBrandSell = true
            this.brandSellId = ''
            this.brandSellName = ''
        },

        // 初始化数据---清除品牌
        formatBrand() {
            this.brandList = []
            this.checkBrand = true
            this.brandName = ''
            this.spuInfoVo.brandId = ''
        },

        // 初始化分类
        formatCategory() {
            this.spuInfoVo.categoryId = 0
            this.spuInfoVo.name = ''
            this.spuInfoVo.parentCid = ''
        },

        // 初始化标题和详细描述
        formatSpu() {
            this.spuInfoVo.spuTitle = ''
            this.spuInfoVo.spuDetail = ''
        },

        // 初始化所有
        formatAll() {
            this.formatAttr()
            this.formatBrand()
            this.formatCategory()
            this.formatSellProduct()
            this.formatSpu()
            // 返回上一页
            this.$router.go(-1)
        },


        // 设置品牌售卖商品名称
        setBrandSellName() {

            for (let i = 0; i < this.brandSellList.length; i++) {
                if (this.brandSellList[i].id == this.brandSellId) {
                    this.brandSellName = this.brandSellList[i].name;
                    this.getBrandCategoryAttr()
                    break;
                }
            }
        },

        // 设置商品品牌提示信息
        setBrandName() {
            let len = this.brandList.length;
            for (let i = 0; i < len; i++) {
                if (this.brandList[i].brandId == this.spuInfoVo.brandId) {
                    this.brandName = this.brandList[i].name;
                    this.getBrandSellProduct();
                    break;
                }
            }
        },
        // --------------------------------------------------------------------------------------------------------------------------------------------------------------
        // --------------------------------------------------------------------------------------------------------------------------------------------------------------
        // --------------------------------------------------------------------------------------------------------------------------------------------------------------
        // 获得分类vo   =====category
        getCategoryVo(categoryVo) {
            this.spuInfoVo.parentCid = categoryVo.parentCid;
            this.spuInfoVo.categoryId = categoryVo.categoryId
            this.spuInfoVo.name = categoryVo.name
            // 查找 通过分类查找品牌
            this.getBrandByCategory(this.spuInfoVo.categoryId)
        },

        // 通过分类获得该分类的所有品牌   =====brand
        getBrandByCategory(categoryId) {
            this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/brand/categoryBrand?categoryId=${this.spuInfoVo.categoryId}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    if (data.data == null || data.data.length <= 0) {
                        this.$message({
                            type: 'warning',
                            message: data.message
                        })
                        this.checkBrand = true;
                        this.brandList = [];
                        // 品牌为空，则清除之前产生的所有数据
                        this.formatBrand();
                        this.formatSellProduct();
                        this.formatAttr();
                        return;
                    }
                    this.brandList = data.data
                    this.setBrandName()
                    this.checkBrand = false;
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },

        // 获得品牌售卖商品 shitouproduct/brandsellproduct
        getBrandSellProduct() {
            this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/brandsellproduct/sellProduct?brandId=${this.spuInfoVo.brandId}&categoryId=${this.spuInfoVo.categoryId}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    if (data.data == null || data.data.length == 0) {
                        this.brandSellList = []
                        this.checkBrandSell = true;
                        // 品牌售卖商品为空，则初始化attr和售卖商品列表
                        this.formatAttr();
                        this.formatSellProduct();
                        return;
                    }
                    this.brandSellList = data.data
                    for (let i = 0; i < this.brandSellList.length; i++) {
                        if (this.brandSellList[i].name == this.spuInfoVo.brandSellName) {
                            this.brandSellName = this.spuInfoVo.brandSellName;
                            this.brandSellId = this.brandSellList[i].id
                        }
                    }
                    this.checkBrandSell = false;
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },

        // 获得该分类下的所有属性,因为该分类的所有品牌享有该分类的所有属性，所以通过分类id索引
        getBrandCategoryAttr() {
            this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/attr/attrByCategoryId?categoryId=${this.spuInfoVo.categoryId}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    if (data.data == null || data.data.length <= 0) {
                        this.attrList = []
                        return;
                    }
                    this.attrList = data.data
                    // 初始化choseAttr
                    this.initChoseAttr()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },

        // 初始化choseAttr
        initChoseAttr() {
            let len = this.attrList.length
            // 循环
            for (let i = 0; i < len; i++) {
                let attrLen = this.attrList[i].splitValue.length
                this.choseAttr[i] = new Array();
                for (let j = 0; j < attrLen; j++) {
                    this.choseAttr[i][j] = false;
                }
            }

            let tag = false;
            for (let f = 0; f < this.spuInfoVo.allAttr.length; f++) {
                for (let i = 0; i < len; i++) {
                    let attrLen = this.attrList[i].splitValue.length
                    tag = false
                    for (let j = 0; j < attrLen; j++) {
                        if (this.spuInfoVo.allAttr[f].value == this.attrList[i].splitValue[j]) {
                            this.choseAttr[i][j] = true;
                            tag = true;
                            break;
                        }
                    }
                    if (tag) break;
                }
            }
        },

        // 通过spuid获取商品信息
        getProductBySpuId() {
            this.$http({
                url: this.$http.adornUrl("/shitou-product/shitouproduct/spuinfo/getProductBySpuId"),
                method: 'post',
                data: this.$http.adornData(this.spuInfoVo)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.spuInfoVo = data.data;
                    this.spuInfoVo.spuDetail = data.data.spuDetail.replaceAll("<br>", "\n")
                    if (this.spuInfoVo.brandId == 0) {
                        this.spuInfoVo.brandId = ''
                    }
                    if (this.spuInfoVo.price == 0) {
                        this.spuInfoVo.price = '';
                    }
                    // 获得最上层的分类category父亲id
                    this.getCategoryPid();

                    // 设置分类
                    this.getCategoryVo({
                        categoryId: this.spuInfoVo.categoryId,
                        parentCid: this.spuInfoVo.parentCid,
                        name: this.spuInfoVo.name
                    })
                    // 获得品牌售卖商品
                    this.getBrandSellProduct()

                    // 获得该分类下的所有属性
                    this.getBrandCategoryAttr()

                    // 展示图片设置
                    this.updateSetFileList();
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message 
                    })
                }

            })
        },

        // 获得最上层的id
        getCategoryPid() {
            this.$http({
                url: this.$http.adornUrl(`/shitou-product/shitouproduct/category/info?categoryId=${this.spuInfoVo.parentCid}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.pparengCid = data.category.parentCid==null?null:data.category.parentCid
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }

            })
        },

        // 用以更新展示图片
        updateSetFileList() {
            let imgs = this.spuInfoVo.imageUrls
            for (let i = 0; i < imgs.length; i++) {
                let index = imgs[i].indexOf('_') + 1;
                let name = imgs[i].substring(index, imgs[i].length)
                this.fileList.push({
                    name: name,
                    url: imgs[i]
                })
            }
        },
    },

    async created() {
        let member = await this.$memberInfo()
        if (member !== null) {
            this.memberVo = member
            this.spuInfoVo.id = member.id
            this.spuInfoVo.spuId = this.$route.query.spuId;
            this.getProductBySpuId()
        }
    }
}
</script>
<style scoped>
@import url("../../utils/css/addproduct.css");
</style>